package xyz.jcat.seata.example.storage.service.impl;

import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import xyz.jcat.common.exception.BusinessException;
import xyz.jcat.common.util.JsonUtils;
import xyz.jcat.mybatis.ServiceImpl;
import xyz.jcat.seata.example.api.dto.StorageDecrDto;
import xyz.jcat.seata.example.storage.domain.dao.IItemStorageDao;
import xyz.jcat.seata.example.storage.domain.po.ItemStoragePo;
import xyz.jcat.seata.example.storage.service.IItemStorageService;

import java.util.Date;

/**
 *
 * @author yueyue
 * auto on 2022-03-16 01:17:30
 */
@Slf4j
@Service
public class ItemStorageService extends ServiceImpl<IItemStorageDao, ItemStoragePo> implements IItemStorageService {

    @Override
    public void decr(StorageDecrDto storageDecrDto) {
        int result = dao.decr(storageDecrDto.getItemId(), storageDecrDto.getNum(), storageDecrDto.getNum(), new Date());
        if(!SqlHelper.retBool(result)) {
            log.error("修改库存异常[decr], storageDecrDto -> ()", storageDecrDto);
            throw new BusinessException("商品库存不足");
        }
    }

    @Override
    public boolean decrItemStorageCommitMethod(BusinessActionContext context) {
        StorageDecrDto storageDecrDto = getStorageDecrDtoByDecrItemStorageBusinessActionContext(context);
        int result = dao.decr(storageDecrDto.getItemId(), 0, 0 - storageDecrDto.getNum(), new Date());
        if(!SqlHelper.retBool(result)) {
            log.error("修改库存异常[decrItemStorageCommitMethod], storageDecrDto -> ()", storageDecrDto);
            return false;
        }
        return true;
    }

    //try阶段库存不足，未改变数据,直接return true
    @Override
    public boolean decrItemStorageRollbackMethod(BusinessActionContext context) {
        return true;
    }

    private StorageDecrDto getStorageDecrDtoByDecrItemStorageBusinessActionContext(BusinessActionContext context) {
        Object storageDecrDtoJson = context.getActionContext("storageDecrDto");
        return JsonUtils.parseObject(storageDecrDtoJson, StorageDecrDto.class);
    }
}
